package com.raincat.multimediapicker;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.raincat.multimediapicker.utils.VideoController;
import com.raincat.multimediapicker.utils.VideoHelper;
import com.raincat.multimediapicker.utils.VideoItem;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/3/27 0027.
 */

public class VideoGridFragment extends Fragment {
    private Context context;

    private GridView gridView;
    private TextView tv_camera;
    private Button btn_sure;

    private GridAdapter gridAdapter;
    private List<VideoItem> dataList = new ArrayList<>();

    private int imgWidth = 0;
    private String path = "";

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = this.getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.picker_fragment_videogrid, container, false);
        gridView = (GridView) view.findViewById(R.id.gridview);
        tv_camera = (TextView) view.findViewById(R.id.tv_camera);
        btn_sure = (Button) view.findViewById(R.id.btn_sure);

        imgWidth = (int) (((PickerActivity) context).getPhoneW() - (25 * ((PickerActivity) context).getScale())) / 4;
        VideoHelper.getInstance(context).getVideoItemList(new VideoHelper.onVideoItemListGetListener() {
            @Override
            public void onFinish(List<VideoItem> videoItemList) {
                dataList = videoItemList;
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        setData();
                    }
                });
            }
        });
        listener();
        return view;
    }

    private void setData() {
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridAdapter = new GridAdapter();
        gridView.setAdapter(gridAdapter);
    }

    private void listener() {
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (VideoController.count != 0) {
                    finishActivity();
                }
            }
        });
        tv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                takeVideoByCamera();
            }
        });
    }

    private void setCount() {
        if (btn_sure != null) {
            if (VideoController.count == 0) {
                btn_sure.setBackgroundResource(R.drawable.picker_btn_disable);
                btn_sure.setText(context.getResources().getString(R.string.picker_OK));
            } else {
                btn_sure.setBackgroundResource(R.drawable.picker_btn_enable);
                btn_sure.setText(context.getResources().getString(R.string.picker_OK) + "(" + VideoController.count + "/" + VideoController.maxCount + ")");
            }
        }
    }

    private void takeVideoByCamera() {
        String SDPATH = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
        File file = new File(SDPATH, String.valueOf(System.currentTimeMillis()) + ".mp4");
        path = file.getPath();
        ContentValues contentValues = new ContentValues(1);
        contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        Uri imageUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

        Intent openCameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        openCameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);// 设置视频的质量，值为0-1，
        openCameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60);// 设置视频的录制长度，s为单位
        openCameraIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, VideoController.maxSize * 1024 * 1024L);// 设置视频文件大小，字节为单位
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(openCameraIntent, 250);
    }

    public void finishActivity() {
        VideoController.takeRealPathList();
        ((PickerActivity) context).finishActivity("VideoList", VideoController.realPathList);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 250) {
                VideoController.addOrRemoveVideoItem(context, path);
                finishActivity();
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
        }
    }

    private class GridAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        GridAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = mInflater.inflate(R.layout.picker_fragment_videogrid_item, parent, false);
                holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
                holder.iv_check = (ImageView) convertView.findViewById(R.id.iv_check);
                holder.rl_check = (RelativeLayout) convertView.findViewById(R.id.rl_check);
                holder.tv_error = (TextView) convertView.findViewById(R.id.tv_error);
                holder.tv_suffix = (TextView) convertView.findViewById(R.id.tv_suffix);

                ViewGroup.LayoutParams LP = holder.iv_img.getLayoutParams();
                LP.height = imgWidth;
                LP.width = imgWidth;
                holder.iv_img.setLayoutParams(LP);

                convertView.setTag(holder);
            } else
                holder = (Holder) convertView.getTag();

            final VideoItem item = dataList.get(position);
            holder.iv_img.setImageBitmap(null);

            if (VideoController.videoItemMap.get(item.videoPath) != null) {
                holder.iv_check.setBackgroundResource(R.drawable.picker_check_enable);
                holder.iv_check.setImageResource(R.mipmap.picker_check);
            } else {
                holder.iv_check.setBackgroundResource(R.drawable.picker_check_disable);
                holder.iv_check.setImageDrawable(null);
            }

            holder.tv_suffix.setText(item.videoDuration);
            holder.rl_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    View view = ((RelativeLayout) v).getChildAt(0);
                    if (VideoController.addOrRemoveVideoItem(context, item)) {
                        ((ImageView) view).setImageResource(R.mipmap.picker_check);
                        view.setBackgroundResource(R.drawable.picker_check_enable);
                    } else {
                        ((ImageView) view).setImageDrawable(null);
                        view.setBackgroundResource(R.drawable.picker_check_disable);
                    }
                    setCount();
                }
            });


            Glide.with(context).asBitmap().load(item.videoPath).into(holder.iv_img);


            ((ViewGroup) convertView).setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            return convertView;
        }

        class Holder {
            public ImageView iv_img, iv_check;
            public TextView tv_error, tv_suffix;
            public RelativeLayout rl_check;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        setCount();
        if (gridAdapter != null)
            gridAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}